# -*- coding:utf-8 -*-

import unittest
import datetime
import time
import sys

from common import api2request

sys.dont_write_bytecode = True

# Virbox LM 平台 OpenAPI V2 应用基地址
appurl = "https://openapi.senseyun.com"

# 使用时应换成自己的 appId 和 appSecret.
# 如果查看 appId/appSecret 请查看文档：https://developer.lm.virbox.com/course/course.html#other
appId = bytes("0b0c24be2c614fa48c2067aedc43ec71").encode("utf-8")
appSecret = bytes("1432c2b485104a9ebecd2019703613e3").encode("utf-8")

# 初始化 api 请求
api2 = api2request.API2Request(appUrl=appurl, appId=appId, appSecret=appSecret)

# 声明测试过程中的中间变量，因为某些接口的参数依赖指定接口的返回数据
# 普通用户的 userId
userid = None
# 影子账号 account
shadowAccountWithDeveloperGuid = None
# 影子账号的 userId
shadowAccountUserId = None
# 软许可模板 id
tidofsoft = None
# 云许可模板 id
tidofcloud = None
# 软许可的唯一 guid
licenseGuid = None
# 标签 id
tagid = None
# 声明中间变量结束


# 获取当前时间
now = int(time.time());

# 声明测试过程中用到的一些数据
# 截取当前时间，用来模拟手机号，手机号必须是1开头的11位数字。
# 正式使用时请使用正确的手机号，否则会影响业务使用

userAccount = "1" + str(now)
# 影子账号
shadowAccount = "OpenAPIV2-"+str(now)
# 产品id, 在此测试使用固定的 id.
licenseId = 17
# 声明测试数据结束

class Test(unittest.TestCase):
    """
    每个模块一个字母，每个模块的测试用例从1开始，依次往后推，以保证执行顺序
    如：用户模块：a
    详细的 OpenAPI 文档请查看：https://developer.lm.virbox.com/doc/OpenAPI-V2.pdf
    """

    # 测试通用账号开始  =====================start
    def test_a_01_adduserofphone(self):
        """
        添加以手机号作账号的用户
        :return:
        """
        user = {
            "userAccount": userAccount,
            "nickname": "kanghl",
            "passwd": "123456",
            "accountType": 2
        }
        result = api2.send('/v2/sv/addUser', user)
        assert result["code"] == 0
        global userid
        userid = result['data']['userId']

    def test_a_02_finduser(self):
        """
        查找用户
        :return:
        """
        conditions = {
            "cellphone": userAccount
        }
        result = api2.send('/v2/sv/findUsers', conditions)
        assert result["data"]["totalCount"] >= 1

    def test_a_03_modifyuserpasswd(self):
        """通用账号的密码修改,修改不了。只允许修改影子账号的密码"""
        userdict = {
            "userAccount": userAccount,
            "passwd": "12345678"
        }
        result = api2.send('/v2/sv/modifyUserPasswd', userdict)
        assert result["code"] == 103

    def test_a_03_mofifyUser(self):
        """修改用户基本信息"""
        userdict = {
            "userId": userid,
            "desc": "修改用户信息"
        }
        result = api2.send('/v2/sv/modifyUser', userdict)
        assert result["code"] == 0

    # 测试通用账号结束======================end

    # 测试影子账号开始  =====================start
    def test_a_05_addshadowuser(self):
        """
        添加影子账号
        :return:
        """
        user = {
            "shadowAccount": shadowAccount,
            "nickname": "kanghl",
            "passwd": "123456",
        }
        result = api2.send('/v2/sv/addShadowUser', user)
        print result
        assert result["code"] == 0
        global shadowAccountWithDeveloperGuid
        shadowAccountWithDeveloperGuid = result["data"]["userAccount"]
        global shadowAccountUserId
        shadowAccountUserId = result["data"]["userId"]

    def test_a_6_modifyshadowuserpasswd(self):
        """
        影子账号的密码修改，修改成功
        :return:
        """
        userdict = {
            "userAccount": shadowAccountWithDeveloperGuid,
            "passwd": "12345678"
        }
        result = api2.send('/v2/sv/modifyUserPasswd', userdict)
        assert result["code"] == 0


    # 测试影子账号结束======================end

    # 测试产品相关 =========================start
    def test_b_1_addproduct(self):
        product = {
            "licenseId": licenseId,
            "productName": '测试API2.0',
            'licenseForm': [1, 2],       # 1: 云锁，2: 软锁
            'pub': '1234',               # 公开区，16进制字符串
            'rom': '123456',             # 只读区，16进制字符串
            'raw': '12345678',           # 读写区，16进制字符串
            'modules': [
                {
                    'moduleId': 1,
                    'moduleName': '高级功能1'
                },
                {
                    'moduleId': 2,
                    'moduleName': '高级功能2'
                },
            ]
        }
        result = api2.send('/v2/sv/addProduct', product)
        assert result["code"] == 0

    def test_b_3_modifyProduct(self):
        modifyproduct = {
            "licenseId": licenseId,
            "productName": '测试API2.0修改产品名称'
        }
        result = api2.send('/v2/sv/modifyProduct', modifyproduct)
        assert result["code"] == 0

    def test_b_4_getproductinfo(self):
        product = {
            "licenseId": licenseId
        }
        result = api2.send('/v2/sv/getProductInfo', product)
        assert result["data"]["licenseId"] == licenseId

    def test_b_5_productlist(self):
        """
        按照产品名称查找产品
        :return: 
        """
        product = {
            "productName": 'API2'
        }
        result = api2.send('/v2/sv/productList', product)
        assert result["data"]["totalCount"] >= 1

    # 测试产品相关==========================end

    # 模板相关测试==========================start
    def test_c_1_addtemplateofcloud(self):
        template = {
            'templateName': '测试API2.0-云锁',
            'licenseId': licenseId,
            'licenseForm': 1,
            'isForever': True,
            'canModify': 1,
            'modules': [
                {
                    'moduleId': 1,
                    'moduleName': '高级功能1'
                }
            ]
        }
        result = api2.send('/v2/sv/addTemplate', template)
        assert result["code"] == 0
        global tidofcloud
        tidofcloud = result["data"]["templateId"]

    def test_c_2_addtemplateofsoft(self):
        template = {
            'templateName': '测试API2.0-软锁',
            'licenseId': licenseId,
            'licenseForm': 2,
            'isForever': False,
            'licStartTimeType': 0,
            'startTime': now,
            'endTime': now+10000,
            "offlineDays": 2,
            "licBindLimit": 2,
            "licBindMaxLimit": 2,
            'licenseMode': 0,
            'pricingMode': 'yearly'
        }
        result = api2.send('/v2/sv/addTemplate', template)
        assert result["code"] == 0
        global tidofsoft
        tidofsoft = result["data"]["templateId"]

    def test_c_3_modifyTemplate(self):
        tempalte = {
            "templateId": tidofsoft,
            "templateName": "测试API2.0-软锁-修改名称",
            'licenseForm': 2,
            'isForever': True,
            "offlineDays": 2,
            "licBindLimit": 2,
            "licBindMaxLimit": 2,
            "canModify": 1,
            'licenseMode': 0,
            'pricingMode': 'once'
        }
        result = api2.send("/v2/sv/modifyTemplate", tempalte)
        assert result["code"] == 0

    def test_c_4_templateList(self):
        template = {
            'licenseId': licenseId
        }
        result = api2.send("/v2/sv/templateList", template)
        assert result["code"] == 0

    def test_c_4_findTemplate(self):
        template = {
            "templateId": tidofsoft
        }
        result = api2.send('/v2/sv/findTemplate', template)
        assert result["code"] == 0
        assert result["data"]["id"] == tidofsoft

    # 模板相关测试============================end

    # 许可相关测试============================start

    def test_d_01_issueLicense(self):
        license = {
            'templateId': tidofcloud,
            'userAccount': userAccount
        }
        result = api2.send("/v2/sv/issueLicense", license)
        assert result["code"] == 0

    def test_d_02_issueLicensetoshadowaccount(self):
        license = {
            'templateId': tidofcloud,
            'userAccount': shadowAccountWithDeveloperGuid
        }
        result = api2.send("/v2/sv/issueLicense", license)
        assert result["code"] == 0

    def test_d_03_issueLicensewithouttemplate(self):
        license = {
            "licenseId": licenseId,
            "isForever": False,
            "licenseForm": 2,
            "userAccount": userAccount,
            "version": 2,
            "startTime": now,
            "endTime": 10000+now,
            "span": 3,
            "offlineDays": 3,
            "licBindLimit": 3,
            "licBindMaxLimit": 3,
            "isOffline": True,
            'licenseMode': 0,
            'pricingMode': 'daily'
        }
        result = api2.send("/v2/sv/issueLicenseByProduct", license)
        assert result["code"] == 0

    def test_d_04_licenseList(self):
        license = {
            'userAccount': userAccount,
            'licenseForms': [2]

        }
        result = api2.send('/v2/sv/licenseList', license)
        assert result["code"] == 0
        global licenseGuid
        licenseGuid = result['data']['licenses'][0]['pubLicenseGuid']

    def test_d_05_updateLicense(self):
        license = {
            "licenseId": licenseId,
            "userAccount": userAccount,
            "licenseForm": 2,
            "version": {
                "op": "set",
                "value": 4
            },
            "span": {
                "op": "set",
                "value": 4
            }
        }
        result = api2.send('/v2/sv/updateLicense', license)
        assert result["code"] == 0

    def test_d_7_licenseUseInfo(self):
        license = {
            'licenseId': licenseId,
            'licenseForm': 2,
            'userAccount': userAccount
        }
        result = api2.send("/v2/sv/licenseUseInfo", license)
        assert result["code"] == 0
        assert result['data']['isUsed'] == False

    def test_d_8_softLockBindList(self):
        license = {
            'licenseGuid': licenseGuid,
        }
        result = api2.send("/v2/sv/softLockbindList", license)
        assert result["code"] == 0

    def test_d_9_softLockBindHistory(self):
        license = {
            'licenseGuid': licenseGuid,
        }
        result = api2.send("/v2/sv/softLockbindHistory", license)
        assert result["code"] == 0

    # 许可相关测试============================end

    # 硬件许可相关测试=========================start

    def test_e_1_addlic(self):
        lic = {
            'pin': '1qaz2wsx3edc4rfv',
            'deviceId': '9733C8010007020510610004000D0017',
            'shellNumber': '099900000039',
            'deviceCert': 'MIIDHDCCAgSgAwIBAgICWTowDQYJKoZIhvcNAQEFBQAwFDESMBAGA1UEAxMJRGV2aWNlIENBMB4XDTE2MDEwNzA3MDczMVoXDTM2MDEwMjA3MDczMVowgY0xCzAJBgNVBAYTAkNOMRAwDgYDVQQIDAdCZWlqaW5nMRAwDgYDVQQHDAdCZWlqaW5nMRIwEAYDVQQKDAlTZW5zZWxvY2sxEjAQBgNVBAsMCVNlbnNlbG9jazEyMDAGA1UEAwwpREVWSUNFSUQtOTczM0M4MDEwMDA3MDIwNTEwNjEwMDA0MDAwRDAwMTcwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCY+BpKeuhlen+jk1NSs1sdfJXBqGtIxhFdMf/73wfRspmF7HI469JFOumo3wInwDPs4sX5jx2/ewOfgw1wAqnmuy677zqN5Flip04touc1qDqx1XajBTy0W1O3ERFS81BNSyblzrFwpzI6vLcjh5xZf5iAPQN8PPRv71XkkG1kgJT1Ekr1BbIiQn29M+tnooRt9OhAe3hQOSu82Llrc0SOSTFAuabFzP8jEn0TeJjxC8J0td+pqa8Yz5VumANqETtPU/RvvcYpLlIUY7iwB1tdIyG4qcC0ZEGEhS5+EEJpG5sVRUzeTJpoZERTzMVS8ud6Dp/1ShIDShWTPBrJv637AgMBAAEwDQYJKoZIhvcNAQEFBQADggEBACzxRH9whSI26EZ5KSMud40PCqtogNj6kgtYSPx11UFHBSLiefqGtZkqGavHrrLdNP+8bEbQgSWnGxyOfsK+0FWZ/5C7Yzn9UfuGGOBhdI7sexr/bkMEkeIyy9D/La0pe4W1LJXD38Z+9tycg4bddGCO/PShuqsrV0VX8fBDI6U7zd8vD9eJpY8O4ppJ9+tPCcH1utYkj9V8nz7mDCg3mrZp+SkqvcUnBvXDJkYU4cF1WjqZRJFMDfZJ5n4I59Ai2IqJMoKZCcERK9blbzCjO4OF+yxCO+MNqiGtilrftcor5zmO253vdyO1EzJG4Un0BdjnTR52cIfUNVUbx+qtbNk=',
            'licenseId': licenseId,
            'force': True,
            'isForever': False,
            'startTime': now,
            'endTime': now+10000,
            'counter': 3,
            'span': 3,
            'concurrent': 10,
            'concurrentType': 'process',
            'module': [1],
            'rom': {
                'data': '1234',
            },
            'raw': {
                'data': '123456',
                'offset': 0,
                'resize': 3
            },
            'pub': {
                'data': '123456',
                'offset': 0,
                'resize': 6
            },
            'licDesc': '添加硬件许可'
        }
        api2.send('/v2/sv/devicelicense/addlic',lic)

    def test_e_2_updatelic(self):
        lic = {
            'pin': '1qaz2wsx3edc4rfv',
            'deviceId': '9733C8010007020510610004000D0017',
            'shellNumber': '099900000039',
            'deviceCert': 'MIIDHDCCAgSgAwIBAgICWTowDQYJKoZIhvcNAQEFBQAwFDESMBAGA1UEAxMJRGV2aWNlIENBMB4XDTE2MDEwNzA3MDczMVoXDTM2MDEwMjA3MDczMVowgY0xCzAJBgNVBAYTAkNOMRAwDgYDVQQIDAdCZWlqaW5nMRAwDgYDVQQHDAdCZWlqaW5nMRIwEAYDVQQKDAlTZW5zZWxvY2sxEjAQBgNVBAsMCVNlbnNlbG9jazEyMDAGA1UEAwwpREVWSUNFSUQtOTczM0M4MDEwMDA3MDIwNTEwNjEwMDA0MDAwRDAwMTcwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCY+BpKeuhlen+jk1NSs1sdfJXBqGtIxhFdMf/73wfRspmF7HI469JFOumo3wInwDPs4sX5jx2/ewOfgw1wAqnmuy677zqN5Flip04touc1qDqx1XajBTy0W1O3ERFS81BNSyblzrFwpzI6vLcjh5xZf5iAPQN8PPRv71XkkG1kgJT1Ekr1BbIiQn29M+tnooRt9OhAe3hQOSu82Llrc0SOSTFAuabFzP8jEn0TeJjxC8J0td+pqa8Yz5VumANqETtPU/RvvcYpLlIUY7iwB1tdIyG4qcC0ZEGEhS5+EEJpG5sVRUzeTJpoZERTzMVS8ud6Dp/1ShIDShWTPBrJv637AgMBAAEwDQYJKoZIhvcNAQEFBQADggEBACzxRH9whSI26EZ5KSMud40PCqtogNj6kgtYSPx11UFHBSLiefqGtZkqGavHrrLdNP+8bEbQgSWnGxyOfsK+0FWZ/5C7Yzn9UfuGGOBhdI7sexr/bkMEkeIyy9D/La0pe4W1LJXD38Z+9tycg4bddGCO/PShuqsrV0VX8fBDI6U7zd8vD9eJpY8O4ppJ9+tPCcH1utYkj9V8nz7mDCg3mrZp+SkqvcUnBvXDJkYU4cF1WjqZRJFMDfZJ5n4I59Ai2IqJMoKZCcERK9blbzCjO4OF+yxCO+MNqiGtilrftcor5zmO253vdyO1EzJG4Un0BdjnTR52cIfUNVUbx+qtbNk=',
            'licenseId': licenseId,
            'force': True,
            'isForever': False,
            'startTime': {
                'op': 'set',
                'value': now
            },
            'endTime': {
                'op': 'inc',
                'value': 100
            },
            'counter': {
                'op': 'dec',
                'value': 1
            },
            'span': {
                'op': 'disable'
            },
            'concurrent': 10,
            'concurrentType': 'process',
            'module': [1],
            'rom': {
                'data': '1234',
            },
            'raw': {
                'data': '123456',
                'offset': 0,
                'resize': 3
            },
            'pub': {
                'data': '123456',
                'offset': 0,
                'resize': 6
            },
            'licDesc': '更新硬件许可'
        }
        api2.send('/v2/sv/devicelicense/updatelic',lic)

    def test_e_3_ctrllic(self):
        lic = {
            'pin': '1qaz2wsx3edc4rfv',
            'deviceId': '9733C8010007020510610004000D0017',
            'shellNumber': '099900000039',
            'deviceCert': 'MIIDHDCCAgSgAwIBAgICWTowDQYJKoZIhvcNAQEFBQAwFDESMBAGA1UEAxMJRGV2aWNlIENBMB4XDTE2MDEwNzA3MDczMVoXDTM2MDEwMjA3MDczMVowgY0xCzAJBgNVBAYTAkNOMRAwDgYDVQQIDAdCZWlqaW5nMRAwDgYDVQQHDAdCZWlqaW5nMRIwEAYDVQQKDAlTZW5zZWxvY2sxEjAQBgNVBAsMCVNlbnNlbG9jazEyMDAGA1UEAwwpREVWSUNFSUQtOTczM0M4MDEwMDA3MDIwNTEwNjEwMDA0MDAwRDAwMTcwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCY+BpKeuhlen+jk1NSs1sdfJXBqGtIxhFdMf/73wfRspmF7HI469JFOumo3wInwDPs4sX5jx2/ewOfgw1wAqnmuy677zqN5Flip04touc1qDqx1XajBTy0W1O3ERFS81BNSyblzrFwpzI6vLcjh5xZf5iAPQN8PPRv71XkkG1kgJT1Ekr1BbIiQn29M+tnooRt9OhAe3hQOSu82Llrc0SOSTFAuabFzP8jEn0TeJjxC8J0td+pqa8Yz5VumANqETtPU/RvvcYpLlIUY7iwB1tdIyG4qcC0ZEGEhS5+EEJpG5sVRUzeTJpoZERTzMVS8ud6Dp/1ShIDShWTPBrJv637AgMBAAEwDQYJKoZIhvcNAQEFBQADggEBACzxRH9whSI26EZ5KSMud40PCqtogNj6kgtYSPx11UFHBSLiefqGtZkqGavHrrLdNP+8bEbQgSWnGxyOfsK+0FWZ/5C7Yzn9UfuGGOBhdI7sexr/bkMEkeIyy9D/La0pe4W1LJXD38Z+9tycg4bddGCO/PShuqsrV0VX8fBDI6U7zd8vD9eJpY8O4ppJ9+tPCcH1utYkj9V8nz7mDCg3mrZp+SkqvcUnBvXDJkYU4cF1WjqZRJFMDfZJ5n4I59Ai2IqJMoKZCcERK9blbzCjO4OF+yxCO+MNqiGtilrftcor5zmO253vdyO1EzJG4Un0BdjnTR52cIfUNVUbx+qtbNk=',
            'ctrlType': 3,
            'startTime': now,
            'endTime': now + 100000,
            'licDesc': '控制许可'
        }
        api2.send('/v2/sv/devicelicense/ctrllic', lic)

    def test_e_4_dellic(self):
        lic = {
            'pin': '1qaz2wsx3edc4rfv',
            'deviceId': '9733C8010007020510610004000D0017',
            'shellNumber': '099900000039',
            'deviceCert': 'MIIDHDCCAgSgAwIBAgICWTowDQYJKoZIhvcNAQEFBQAwFDESMBAGA1UEAxMJRGV2aWNlIENBMB4XDTE2MDEwNzA3MDczMVoXDTM2MDEwMjA3MDczMVowgY0xCzAJBgNVBAYTAkNOMRAwDgYDVQQIDAdCZWlqaW5nMRAwDgYDVQQHDAdCZWlqaW5nMRIwEAYDVQQKDAlTZW5zZWxvY2sxEjAQBgNVBAsMCVNlbnNlbG9jazEyMDAGA1UEAwwpREVWSUNFSUQtOTczM0M4MDEwMDA3MDIwNTEwNjEwMDA0MDAwRDAwMTcwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCY+BpKeuhlen+jk1NSs1sdfJXBqGtIxhFdMf/73wfRspmF7HI469JFOumo3wInwDPs4sX5jx2/ewOfgw1wAqnmuy677zqN5Flip04touc1qDqx1XajBTy0W1O3ERFS81BNSyblzrFwpzI6vLcjh5xZf5iAPQN8PPRv71XkkG1kgJT1Ekr1BbIiQn29M+tnooRt9OhAe3hQOSu82Llrc0SOSTFAuabFzP8jEn0TeJjxC8J0td+pqa8Yz5VumANqETtPU/RvvcYpLlIUY7iwB1tdIyG4qcC0ZEGEhS5+EEJpG5sVRUzeTJpoZERTzMVS8ud6Dp/1ShIDShWTPBrJv637AgMBAAEwDQYJKoZIhvcNAQEFBQADggEBACzxRH9whSI26EZ5KSMud40PCqtogNj6kgtYSPx11UFHBSLiefqGtZkqGavHrrLdNP+8bEbQgSWnGxyOfsK+0FWZ/5C7Yzn9UfuGGOBhdI7sexr/bkMEkeIyy9D/La0pe4W1LJXD38Z+9tycg4bddGCO/PShuqsrV0VX8fBDI6U7zd8vD9eJpY8O4ppJ9+tPCcH1utYkj9V8nz7mDCg3mrZp+SkqvcUnBvXDJkYU4cF1WjqZRJFMDfZJ5n4I59Ai2IqJMoKZCcERK9blbzCjO4OF+yxCO+MNqiGtilrftcor5zmO253vdyO1EzJG4Un0BdjnTR52cIfUNVUbx+qtbNk=',
            'licenseId': licenseId,
            'force': True,
            'licDesc': '删除许可'
        }
        api2.send('/v2/sv/devicelicense/dellic', lic)

    # 硬件许可相关测试==========================end


    # 标签相关测试============================start

    def test_f_1_addtag(self):
        """
        添加标签
        :return:
        """
        tag = {
            'name': '测试标签'
        }
        result = api2.send("/v2/sv/addTag", tag)
        assert result["code"] == 0
        global tagid
        tagid = result['data']['id']

    def test_f_2_updatetag(self):
        """
        修改标签
        :return:
        """
        tag = {
            'id': tagid,
            'name': '测试标签修改'
        }

        result = api2.send('/v2/sv/updateTag',tag)
        assert result['code']==0

    def test_f_3_findtags(self):
        """
        查找标签
        :return:
        """
        tag = {
            'name': '测试'
        }
        result = api2.send('/v2/sv/findTags', tag)
        assert result['code'] == 0
        assert len(result['data']) == 1

    def test_f_4_deletatag(self):
        """"
        删除标签
        """
        tag = {
            'id': tagid
        }
        result = api2.send('/v2/sv/deleteTag', tag)
        assert result['code'] == 0

    # 标签相关测试============================end

    # 数据清理==========================start
    # 主要清理用户、产品、模板
    def test_j_1_deleteLicenseOfCloud(self):
        license = {
            "licenseId": licenseId,
            "userAccount": userAccount,
            "licenseForm": 1,
        }

        result = api2.send("/v2/sv/deleteLicense", license)
        assert result["code"] == 0

    def test_j_2_deleteTemplateofsoft(self):
        template = {
            'templateId': tidofsoft
        }
        result = api2.send('/v2/sv/deleteTemplate',template)
        assert result["code"] == 0

    def test_j_3_deleteTemplateofCloud(self):
        template = {
            'templateId': tidofcloud
        }
        result = api2.send('/v2/sv/deleteTemplate', template)
        assert result["code"] == 0

    def test_j_4_deleteproduct(self):
        product = {
            "licenseId": licenseId
        }
        result = api2.send('/v2/sv/deleteProduct', product)
        assert result["code"] == 0

    def test_j_5_deleteshadowuser(self):
        userdic = {
            "userId": shadowAccountUserId
        }
        result = api2.send('/v2/sv/deleteUser', userdic)
        assert result["code"] == 0

# 数据清理===========================end

if __name__ == '__main__':
    unittest.main()
